////连接数据库
var db = openDatabase('mydb', '1.0', 'WJN_DB', 2 * 1024 * 1024);
//var msg;

db.transaction(function(tx) {
	tx.executeSql('SELECT * FROM t_pc where id =' + getPar("id"), [], function(tx, results) {
		var len = results.rows.length,
			i;
		for(i = 0; i < len; i++) {
			document.querySelector('#main').innerHTML += "<img src='" + results.rows.item(i).img + "' width='90%' />" +
				"<input type='hidden' name='id' id='id' value='" + results.rows.item(i).id + "' />" +
				"<p>商品名：" + results.rows.item(i).name + " </p>" +
				"<p>品牌：" + results.rows.item(i).branch + "</p>" +
				"<p>价格：" + results.rows.item(i).price + "</p>" +
				"<button onclick='javascript:addToCart(" + results.rows.item(i).id + ");' class='ui-btn ui-shadow ui-corner-all ui-btn-icon-left ui-icon-shop' style='width:40%'>加入购物车</button>";
		}
	}, null);
});

function addToCart(id) {
	if(sessionStorage.getItem('user') == null) {
		alert("请先登录！");
		window.location.href = 'login.html';
	} else {
		var userJsonStr = sessionStorage.getItem('user');
		userEntity = JSON.parse(userJsonStr);
		var u_id = userEntity.id; //获取当前用户id
		var sql = 'SELECT * FROM t_cart where pc_id =' + id + ' and u_id = ' + u_id;

		db.transaction(function(tx) {
			tx.executeSql(sql, [], function(tx, results) {
				if(results.rows.length > 0) { // 购物车中已存在 合并购物车
					var updateSql = 'update t_cart set count = count + 1 where type = 0 and id = ' + results.rows.item(0).id;
					tx.executeSql(updateSql);
					window.location.href = 'index.html#pageThree';
				} else { // 不存在插入新数据
					//计算id
					tx.executeSql('select * from t_cart', [], function(tx, results) {
						var len = results.rows.length; //当前cart的记录数
						len = len + 1; //新的id
						var insertSql = 'insert into t_cart (id,u_id,pc_id,count,type) values(' + len + ',' + u_id + ',' + id + ', 1 , 0)';
						tx.executeSql(insertSql);
						window.location.href = 'index.html#pageThree';
					}, null);

				}
			}, null);

		});

	}
}